﻿using System;
using System.Linq;
using System.Windows;
using CCWP7.Model;
using System.Diagnostics;
using System.Collections.Generic;
using Caliburn.Micro;

namespace CCWP7.CaliburnMicro
{
    public class ServerPageViewModel : Screen
    {
        private const string STR_XmlServerReportAspx = "/XmlServerReport.aspx";
        readonly IServerDataManager _serverDataManager;
        readonly INavigationService _navigationService;
        readonly Func<ServerProjectsViewModel> _projectsFactory;
        readonly Func<ReadServer> _readServerFactory;

        public ServerPageViewModel(IServerDataManager serverDataManager,
        INavigationService navigationService,
        Func<ServerProjectsViewModel> projectsFactory,
        Func<ReadServer> readServerFactory)
        {
            Debug.Assert(navigationService != null, "navigationService is null.");
            Debug.Assert(readServerFactory != null, "readServerFactory is null.");
            Debug.Assert(projectsFactory != null, "projectsFactory is null.");
            Debug.Assert(serverDataManager != null);

            _serverDataManager = serverDataManager;
            _navigationService = navigationService;
            _projectsFactory = projectsFactory;
            _readServerFactory = readServerFactory;
        }

        Server _server;
        protected override void OnActivate()
        {
            try
            {
                if (string.IsNullOrEmpty(Id))
                {
                    MessageBox.Show("Id for the server was not provided, please try refreshing from home page");

                    _navigationService.GoBack();
                    return;
                }
                var server = _serverDataManager.Servers.FirstOrDefault(s => s.Id == Id);

                if (server == null)
                {
                    MessageBox.Show(string.Format("Could not find server with Id: {0}, please try refreshing from home page", Id));

                    _navigationService.GoBack();
                    return;
                }

                _server = server;
                Projects = _projectsFactory();
                Projects.ServerReport = _server.Report;

                base.OnActivate();

                Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to display server information, please try refreshing from home page: " + ex.Message, "server page", MessageBoxButton.OK);
            }
        }

        public string Id { get; set; }

        public string ServerUri
        {
            get
            {
                if (_server == null)
                    return string.Empty;

                if (_server.Uri.EndsWith(STR_XmlServerReportAspx))
                    return _server.Uri.Replace(STR_XmlServerReportAspx, string.Empty);
                return _server.Uri;
            }
        }
        public string LastRefresh
        {
            get
            {
                return _server != null && _server.LastReportRead.HasValue ? _server.LastReportRead.Value.ToString() : "never";
            }
        }

        public IQueueReport[] Queues
        {
            get
            {
                return _server != null ? _server.Report.Queues : new IQueueReport[0];
            }
        }
        public ServerProjectsViewModel Projects { get; private set; }

        public IEnumerable<IResult> RefreshServerInfo()
        {
            if (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                yield return new SetVisualState("Refreshing");

                var readServer = _readServerFactory();
                readServer.Server.Name = _server.Name;
                readServer.Server.Uri = _server.Uri;
                yield return readServer;

                _server = readServer.Server;
                Refresh();

                yield return new SetVisualState("Normal");
            }
            else
                ReportNetworkNotAvailable();
        }

        public void RemoveServer()
        {
            var result = MessageBox.Show("Are you sure you want to remove this server?", "Remove " + _server.Name, MessageBoxButton.OKCancel);

            if (result == MessageBoxResult.OK)
            {
                _serverDataManager.RemoveServer(_server);

                _navigationService.GoBack();
            }
        }

        public void NavigateToServerUri()
        {
            if (string.IsNullOrEmpty(ServerUri))
                MessageBox.Show("Could not navigate to unknown server uri, try refreshing");

            if (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                _navigationService.Navigate(new Uri("/BrowserPage.xaml?Uri=" + Uri.EscapeDataString(ServerUri), UriKind.Relative));
            else
                ReportNetworkNotAvailable();
        }

        static void ReportNetworkNotAvailable()
        {
            MessageBox.Show("Network not available, please try again later");
        }
    }
}

